//
// Test Arduino sketch for GP2Y1010AU0F dust sensor
// 
// original code created by SenSorApp.net
//     http://sensorapp.net/?p=479
// LedControl Library is from Arduino playground
//     http://www.arduino.cc/playground/Main/LedControl
//

#include "LedControl.h"

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int dustPin=0;      // analog pin # for input
int sensorLedPin=6;     // power internal LED of sensor
int indicatorPin = 13;


#define SENSE_CNT 3

int delayTime=280;  // microseconds
int delayTime2=27;  // (40 - 13) microseconds
float offTime=9680; // microseconds
int sleepTime=3000;
// LedControl(DataIn, CLK, LOAD, # of MAX72xx)
LedControl lc=LedControl(4,2,3,1);

void setup(){
  Serial.begin(9600);
  pinMode(sensorLedPin,OUTPUT);
  pinMode(indicatorPin,OUTPUT);


  // set ADC prescale to 16 (default is 128)
  // this reduce reading time from 104 usec to 13 usec (in 16MHz environment)
  sbi(ADCSRA,ADPS2) ;
  cbi(ADCSRA,ADPS1) ;
  cbi(ADCSRA,ADPS0) ;


  /*
   The MAX72XX is in power-saving mode on startup,
   we have to do a wakeup call
   */
  lc.shutdown(0,false);
  /* Set the brightness to a medium values */
  lc.setIntensity(0,2);
  /* and clear the display */
  lc.clearDisplay(0);
}

void loop(){
  int dustVal = senseData();
  Serial.print("sensor read :");
  Serial.println(dustVal);
  displayVal(dustVal);
  
  
  delay(sleepTime);
}

int senseData()
{
  int v ; 
  int vtemp[SENSE_CNT];
  int s=0;
  
  digitalWrite(indicatorPin, HIGH);

  for (int i=0 ; i<SENSE_CNT ; i++) {
    // sensorLedPin is any digital pin on the arduino connected to Pin 3 on the sensor
    digitalWrite(sensorLedPin,LOW); // power on the LED
    delayMicroseconds(delayTime);
    vtemp[i]=analogRead(dustPin); // read the dust value via pin 5 on the sensor
    delayMicroseconds(delayTime2);
    digitalWrite(sensorLedPin,HIGH); // turn the LED off
    delayMicroseconds(offTime);

  }
  digitalWrite(indicatorPin, LOW);
  for (int i=0; i< SENSE_CNT ; i++) {
    s += vtemp[i];
    Serial.print(vtemp[i]);
    Serial.print (" ");
  }
  Serial.println();
  
  return s/SENSE_CNT;
}
void displayVal(int v) {
  int s0, s1, s2;

  if ( v > 1000 ) {
    s0 = 9;
    s1 = 9;
    s2 = 9;
  } 
  else {
    if ( v >= 100 )  {
      s0 = v / 100;
    } 
    else {
      s0 = 0 ;
    }
    if (v >= 10) {
      s1 =  (v - s0 * 100 ) / 10 ;
    } 
    else {
      s1 = 0 ;
    }
    s2 = (v - s0 * 100 - s1 * 10);
  }

  if ( s0 == 0 ) {
    lc.setChar(0, 0, ' ', false);
    if ( s1 == 0 ) {
      lc.setChar(0, 1, ' ', false);
    }  
    else {
      lc.setDigit(0, 1, s1, false);
    }
    lc.setDigit(0, 2, s2, false);
  } 
  else {
    lc.setDigit(0, 0, s0, false);
    lc.setDigit(0, 1, s1, false);
    lc.setDigit(0, 2, s2, false);
  }
}




